<?php  if (!defined('BASEPATH') || !defined('CRON')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/main.php';

/**
 * Контроллер создания карты сайта
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Cron_Sitemap extends Main {
   
   /**
    * Конструктор класса
    *
    * @access public
    * @return Cron_Sitemap
    */
   function Cron_Sitemap() {
      parent::Main();
   } // end Cron_Sitemap
   
   /**
    * Метод по умолчанию
    *
    * @access public
    */
   function index() {
      // Составляем массив ссылок
      $links = array();
      
      // Сначала добавляем страницы
      // Получаем список меню
      $this->load->model('m_table');
      $this->load->helper('content');
      $this->m_table->set_table('menus');
      $this->m_table->add_restriction('status', 'active'); 
      $this->m_table->add_sort('position');
      $this->m_table->load_results();
      $menus = $this->m_table->get_results();
      
      // Получаем список страниц для sitemap
      $this->m_table->set_table('contents');
      foreach ($menus as $result) {
         $this->m_table->clean();
         $this->m_table->add_restriction('id_menu', $result['id_menu']);
         $this->m_table->add_restriction('status', 'active'); 
         $this->m_table->add_sort('position');
         $this->m_table->load_results();
         $contents = $this->m_table->get_results();
         foreach ($contents as $row) {
            $link = array(
               'loc'        => str_replace('{%base_url%}', base_url(), get_url($row)),
               'lastmod'    => mdate('%Y-%m-%dT%H:%i:%s%P', $row['datetime']),
               'changefreq' => 'weekly',
               'priority'   => 'main' == $row['name'] ? '1.0' : '0.8'
            );
            array_push($links, $link);
         }
      }
      
      // Получаем страницы с жанрами
      $this->db->select('g.id_genre AS id, g.title, g.slug, COUNT(v.id_video) AS count', false)
         ->from('genres g')
         ->join('video_genres vg', 'vg.id_genre = g.id_genre')
         ->join('videos v', 'vg.id_video = v.id_video')
         ->where('v.status', 'active')
         ->where('v.num_torrents >', 0)
         ->group_by('g.id_genre')
         ->order_by('count', 'desc');
      $query = $this->db->get();
      if (0 < $query->num_rows()) {
         $items = $query->result_array();
         foreach ($items as $row) {
            $date = new DateTime();
            $link = array(
               'loc'        => create_link('genre', $row['slug']),
               'lastmod'    => $date->format(DateTime::RFC3339),
               'changefreq' => 'weekly',
               'priority'   => '0.4'
            );
            array_push($links, $link);
         }
      }
      
      // Получаем страницы со странами
      $this->db->select('c.id_country AS id, c.title, c.slug, COUNT(v.id_video) AS count', false)
         ->from('countries c')
         ->join('video_countries vc', 'vc.id_country = c.id_country')
         ->join('videos v', 'vc.id_video = v.id_video')
         ->where('v.status', 'active')
         ->where('v.num_torrents >', 0)
         ->group_by('c.id_country')
         ->order_by('count', 'desc');
      $query = $this->db->get();
      if (0 < $query->num_rows()) {
         $items = $query->result_array();
         foreach ($items as $row) {
            $date = new DateTime();
            $link = array(
               'loc'        => create_link('country', $row['slug']),
               'lastmod'    => $date->format(DateTime::RFC3339),
               'changefreq' => 'weekly',
               'priority'   => '0.4'
            );
            array_push($links, $link);
         }
      }
      
      // Получаем страницы с видео
      $this->m_table->set_table('videos');
      $this->m_table->add_restriction('status', 'active');
      $this->m_table->add_restriction('num_torrents', 0, '>');
      $this->m_table->add_sort('date_created', false);
      $this->m_table->load_results();
      $contents = $this->m_table->get_results();
      foreach ($contents as $row) {
         $date = new DateTime($row['date_created']);
         $link = array(
            'loc'        => create_link('video', 'index', array('id' => $row['id_video'])),
            'lastmod'    => $date->format(DateTime::RFC3339),
            'changefreq' => 'weekly',
            'priority'   => '0.6'
         );
         array_push($links, $link);
      }
      
      // Строим XML файл
      $file = tempnam(sys_get_temp_dir(), 'sitemap');
      if (false !== ($fh = fopen($file, 'w'))) {
         fwrite($fh, '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n");
         foreach ($links as $link) {
            fwrite($fh, "<url>");
            foreach ($link as $key => $val) {
               fwrite($fh, "<$key>" . htmlspecialchars($val) . "</$key>");
            }
            fwrite($fh, "</url>\n");
         }
         fwrite($fh, '</urlset>');
         fclose($fh);
      }
      
      // Переносим в sitemap.xml
      @unlink($this->config->item('sitemap_file'));
      if (rename($file, $this->config->item('sitemap_file'))) {
         @chmod($this->config->item('sitemap_file'), 0777);
      }
      
      echo 'done';
   } // end index
   
}
